#include "network.h"
#define  IP_SIZE   20    //10.1.1.100  255.255.255.255

int get_local_ip(const char *eth_inf, char *ip)
{
    int sd;
    struct sockaddr_in sin;
    struct ifreq ifr;

    sd = socket(AF_INET, SOCK_DGRAM, 0);
    if (-1 == sd)
    {
        printf("socket error: %s\n", strerror(errno));
        return -1;
    }

    strncpy(ifr.ifr_name, eth_inf, IFNAMSIZ);
    ifr.ifr_name[IFNAMSIZ - 1] = 0;

    // if error: No such device
    if (ioctl(sd, SIOCGIFADDR, &ifr) < 0)
    {
        printf("ioctl error: %s\n", strerror(errno));
        close(sd);
        return -1;
    }

    memcpy(&sin, &ifr.ifr_addr, sizeof(sin));
    snprintf(ip, IP_SIZE, "%s", inet_ntoa(sin.sin_addr));

    close(sd);
    return 0;
}


int tcp_init(const char* ip,  int port) //用于初始化操作
{
    int iSockOptVal = 1;
    int sfd= socket(AF_INET,SOCK_STREAM,0);
    if(sfd== -1)
    {
        perror("socket");
        return -1;
    }
    if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &iSockOptVal, sizeof(iSockOptVal)) == -1)
	{
        perror("setsockopt fail");
        close(sfd);
        return -1;
    }	
	struct sockaddr_in serveraddr;
    memset(&serveraddr,0,sizeof(struct sockaddr));
    serveraddr.sin_family=AF_INET;
    serveraddr.sin_port=htons(port);
    inet_pton(AF_INET, ip, &serveraddr.sin_addr.s_addr);
    if (bind(sfd,(struct sockaddr*)&serveraddr,sizeof(struct sockaddr)) == -1)
    {
         perror("soft bind");
         printf(" %s, %d bind socket() fail ,....\r\n",ip,port);
         close(sfd);
         return -1;
    }
    if(listen(sfd,1)==-1)  
    {
        perror("soft listen");
        printf("listen socket() fail ....");
        close(sfd);
        return -1;
    }
	return sfd;
}

int check_socket_connect(int sockfd) 
{
    int ret = 0;
    struct tcp_info info;
    int len = sizeof(info);
    getsockopt(sockfd, IPPROTO_TCP, TCP_INFO, (void *) &info, (socklen_t *) &len);
    if (info.tcpi_state == TCP_ESTABLISHED) 
	{
        ret = 1;
    } else {
        ret = -1;
    }
    return ret;

}

int client_socket_init(void)
{
	int iSockOptVal = 1;
	int vclientfd = socket(AF_INET,SOCK_STREAM,0);
    if(vclientfd== -1)
    {
        perror("socket");
        return -1;
    }
    if (setsockopt(vclientfd, SOL_SOCKET, SO_REUSEADDR, &iSockOptVal, sizeof(iSockOptVal)) == -1)
	{
        perror("setsockopt fail");
        close(vclientfd);
        return -1;
    }
	return vclientfd;
}
int client_socket_connect_to_server(int vclientfd,char *ip,int port)
{
	struct sockaddr_in serveraddr;
    memset(&serveraddr,0,sizeof(struct sockaddr));
    serveraddr.sin_family=AF_INET;
    serveraddr.sin_port=htons(port);
    inet_pton(AF_INET, ip, &serveraddr.sin_addr.s_addr);
	if(connect(vclientfd,(struct sockaddr *)&serveraddr,sizeof(serveraddr)) < 0)
    {
        return -1;
    }
	return vclientfd;
	
}

